// goods-detail.js
Page({
    data: {
        goods: {},           // 商品数据
        currentSpec: null,   // 当前选中的规格
        isCollected: false,  // 是否已收藏
        showSpecModal: false,// 是否显示规格选择浮层
    },

    onLoad(options) {
        // 调用封装的函数获取数据（后续替换为 wx.request）
        const goodsData = this.getGoodsData();
        this.setData({
            goods: goodsData,
            currentSpec: goodsData.specs[0], // 默认选中第一个规格
        });
    },

    /**
     * 封装模拟数据
     * @returns {object} 商品数据
     */
    getGoodsData() {
        return {
            id: 1,
            title: "专业牙齿美白护理套装 天然成分 健康护齿",
            subtitle: "温和去渍，亮白牙齿，不伤牙龈",
            currentPrice: 199,
            originalPrice: 229,
            discount: 8.7,
            tags: ["健康优选", "限时特惠", "新品"],
            rating: 4.8,
            sales: 2356,
            stock: 100,
            brand: "牙健乐",
            brandId: 101, // 店铺ID
            // 轮播图
            swiperImgs: [
                "/assets/images/my/avatar.jpg",
                "/assets/images/my/avatar.jpg",
                "/assets/images/my/avatar.jpg",
            ],
            // 商品详情
            detail: {
                description:
                    "本产品采用先进牙齿护理技术，含天然植物成分，有效去除牙渍、美白牙齿，同时保护牙龈健康。使用方法：每天早晚各一次，取适量产品涂抹于牙刷，轻刷2-3分钟后漱口，坚持两周可见明显效果。",
                features: [
                    "天然成分，温和不刺激",
                    "有效去除咖啡、茶渍、烟渍",
                    "亮白牙齿，提升自信",
                    "保护牙龈，预防牙周病",
                ],
                specifications: [
                    { name: "产品名称", value: "牙齿美白护理套装" },
                    { name: "净含量", value: "100g" },
                    { name: "保质期", value: "2年" },
                    { name: "适用人群", value: "所有人群" },
                    { name: "产地", value: "中国" },
                ],
                detailImgs: [
                    "/assets/images/my/avatar.jpg",
                    "/assets/images/my/avatar.jpg",
                    "/assets/images/my/avatar.jpg",
                ],
            },
            // 规格选择
            specs: [
                { id: 1, name: "单支装", price: 199, stock: 50 },
                { id: 2, name: "两支装（赠牙刷）", price: 379, stock: 30 },
                { id: 3, name: "家庭装（三支装）", price: 559, stock: 20 },
            ],
            // 用户评价
            comments: [
                {
                    id: 1,
                    avatar: "/assets/images/my/avatar.jpg",
                    name: "用户A",
                    rating: 5,
                    time: "2025-10-15",
                    content: "用了一周，牙齿明显变白，牙龈无不适，非常推荐！",
                    images: ["/assets/images/my/avatar.jpg"],
                },
                {
                    id: 2,
                    avatar: "/assets/images/my/avatar.jpg",
                    name: "用户B",
                    rating: 5,
                    time: "2025-10-10",
                    content: "套装很划算，赠的牙刷也好用，会回购～",
                    images: [],
                },
                {
                    id: 3,
                    avatar: "/assets/images/my/avatar.jpg",
                    name: "用户C",
                    rating: 4,
                    time: "2025-10-05",
                    content: "效果不错，希望多出些规格选择～",
                    images: ["/assets/images/my/avatar.jpg"],
                },
            ],
        };
    },

    /**
     * 打开规格选择浮层
     */
    // 打开浮层：确保状态正确更新
    openSpecModal() {
        this.setData({
            showSpecModal: true
        });
        // 可选：强制聚焦内容区，确保点击有效
        wx.createSelectorQuery().select('.modal-content').boundingClientRect(rect => {
            if (rect) {
                // 模拟点击内容区（可选，解决部分机型聚焦问题）
            }
        }).exec();
    },

    /**
     * 关闭规格选择浮层
     */
    closeSpecModal() {
        this.setData({
            showSpecModal: false
        });
    },

    /**
     * 选择规格
     * @param {object} e 事件对象
     */
    selectSpec(e) {
        const specId = e.currentTarget.dataset.id;
        const currentSpec = this.data.goods.specs.find((spec) => spec.id === specId);
        if (currentSpec) { // 增加判断，避免空值
            this.setData({ currentSpec });
        }
    },

    /**
     * 加入购物车
     */
    addToCart() {
        wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
        });
        this.closeSpecModal(); // 关闭浮层
    },

    /**
     * 立即购买
     */
    buyNow() {
        // wx.navigateTo({
        //     url: `/pages/order-confirm/order-confirm?goodsId=${this.data.goods.id}&specId=${this.data.currentSpec.id}`,
        // });
        wx.navigateTo({
          url: '/pages/business/order-confirm/order-confirm',
        })
        this.closeSpecModal(); // 关闭浮层
    },

    /**
     * 切换收藏状态
     */
    toggleCollection() {
        this.setData({
            isCollected: !this.data.isCollected,
        });
        wx.showToast({
            title: this.data.isCollected ? "收藏成功" : "取消收藏",
            icon: "none",
        });
    },

    /**
     * 跳转到店铺页面
     */
    goToShop() {
        wx.navigateTo({
            // url: `/pages/shop/shop?shopId=${this.data.goods.brandId}`,
            url:'/pages/business/shop/shop'
        });
    },

    /**
     * 联系客服
     */
    contactService() {
        wx.showModal({
            title: "联系客服",
            content: "是否要联系客服？",
            success(res) {
                if (res.confirm) {
                    // 模拟联系客服
                    wx.showToast({
                        title: "正在连接客服...",
                        icon: "none",
                    });
                }
                wx.navigateTo({
                  url: '/pages/business/customer-service/customer-service',
                })
            },
        });
    },

    /**
     * 查看全部评价
     */
    viewAllComments() {
        wx.navigateTo({
            url: `/pages/comments/comments?goodsId=${this.data.goods.id}`,
        });
    },

    /**
     * 分享
     */
    onShare() {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
    }
});